﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using GaiNo.Core.Helpers;
using GaiNo.Core;
using GaiNo.Core.Extensions;
using GaiNo.Core.Result;
using GaiNo.Core.Services;
namespace GaiNo.Core.Filters
{
    /// <summary>
    /// 用户授权安全过滤机制
    /// </summary>
    public class AuthorizationActionFilter : FilterAttribute, IAuthorizationFilter
    {
        private string _host_name = string.Empty;
        private bool _single = false;
        private IUser _user = null;
        public AuthorizationActionFilter()
        {
           
        }
        public AuthorizationActionFilter(string host_name)
        {
            _host_name = host_name;
        }
        public AuthorizationActionFilter(bool single)
        {
            _single = single;
        }
        #region IAuthorizationFilter 成员

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string url = filterContext.HttpContext.Request.Url.AbsolutePath;
            string loginUrl = ConfigHelper.GetString("LOGIN_URL");
            if (!ApplicationContext.Current.User.IsAuthenticated)
            {
                if (_host_name.IsNullOrEmpty())
                    _host_name = filterContext.HttpContext.Request.Url.GetSLD();
                url = string.Format("{0}?returnUrl={1}&from={2}", loginUrl, url, _host_name);
                filterContext.Result = new RedirectResult(url);
            }
            else
            {
                _user = ApplicationContext.Current.User;
                string controller = filterContext.RouteData.Values["controller"].ToString();
                string action = filterContext.RouteData.Values["action"].ToString();
                if (_single && !_user.CheckPermission(controller))
                {
                    filterContext.Result = new UnauthorizedResult();
                }
                else if (!_single && !_user.CheckPermission(controller, action))
                    filterContext.Result = new UnauthorizedResult();
            }
        }

        #endregion
    }
}
